"""
Kubernetes资源工具模块
"""
from typing import Dict, List, Any, Optional, Tuple, Union
import yaml
import json
import jsonschema
import deepdiff
import copy
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

class ResourceValidator:
    """资源验证器"""
    
    def __init__(self):
        """初始化验证器"""
        self.schemas = self._load_schemas()
    
    def _load_schemas(self) -> Dict[str, Dict]:
        """
        加载JSON Schema
        
        Returns:
            Schema字典
        """
        # TODO: 从文件加载实际的schema
        return {
            "Deployment": {
                "type": "object",
                "required": ["apiVersion", "kind", "metadata", "spec"],
                "properties": {
                    "apiVersion": {"type": "string"},
                    "kind": {"const": "Deployment"},
                    "metadata": {
                        "type": "object",
                        "required": ["name"],
                        "properties": {
                            "name": {"type": "string"},
                            "namespace": {"type": "string"}
                        }
                    },
                    "spec": {
                        "type": "object",
                        "required": ["replicas", "selector", "template"],
                        "properties": {
                            "replicas": {"type": "integer", "minimum": 0},
                            "selector": {"type": "object"},
                            "template": {"type": "object"}
                        }
                    }
                }
            },
            "Service": {
                "type": "object",
                "required": ["apiVersion", "kind", "metadata", "spec"],
                "properties": {
                    "apiVersion": {"type": "string"},
                    "kind": {"const": "Service"},
                    "metadata": {
                        "type": "object",
                        "required": ["name"],
                        "properties": {
                            "name": {"type": "string"},
                            "namespace": {"type": "string"}
                        }
                    },
                    "spec": {
                        "type": "object",
                        "required": ["ports"],
                        "properties": {
                            "ports": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "required": ["port"],
                                    "properties": {
                                        "port": {"type": "integer"},
                                        "targetPort": {"type": "integer"}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    
    def validate(self, resource: Dict[str, Any]) -> Tuple[bool, List[str]]:
        """
        验证资源
        
        Args:
            resource: 资源定义
            
        Returns:
            (是否有效, 错误消息列表)
        """
        try:
            kind = resource.get("kind")
            if not kind:
                return False, ["缺少kind字段"]
            
            schema = self.schemas.get(kind)
            if not schema:
                return False, [f"不支持的资源类型: {kind}"]
            
            validator = jsonschema.Draft7Validator(schema)
            errors = list(validator.iter_errors(resource))
            
            if errors:
                return False, [str(error) for error in errors]
            
            return True, []
        except Exception as e:
            logger.error(f"验证资源时出错: {str(e)}")
            return False, [str(e)]

class ResourceConverter:
    """资源转换器"""
    
    def __init__(self):
        """初始化转换器"""
        self.converters = {
            "yaml": self._to_yaml,
            "json": self._to_json,
            "dict": self._to_dict
        }
    
    def convert(
        self,
        resource: Union[Dict[str, Any], str],
        target_format: str
    ) -> Union[Dict[str, Any], str]:
        """
        转换资源格式
        
        Args:
            resource: 资源定义或字符串
            target_format: 目标格式
            
        Returns:
            转换后的资源
        """
        # 如果输入是字符串，先解析为字典
        if isinstance(resource, str):
            try:
                if resource.strip().startswith("{"):
                    resource = json.loads(resource)
                else:
                    resource = yaml.safe_load(resource)
            except Exception as e:
                logger.error(f"解析资源时出错: {str(e)}")
                raise
        
        # 获取转换器
        converter = self.converters.get(target_format.lower())
        if not converter:
            raise ValueError(f"不支持的格式: {target_format}")
        
        # 执行转换
        return converter(resource)
    
    def _to_yaml(self, resource: Dict[str, Any]) -> str:
        """转换为YAML格式"""
        return yaml.dump(resource, allow_unicode=True)
    
    def _to_json(self, resource: Dict[str, Any]) -> str:
        """转换为JSON格式"""
        return json.dumps(resource, ensure_ascii=False, indent=2)
    
    def _to_dict(self, resource: Dict[str, Any]) -> Dict[str, Any]:
        """转换为字典格式"""
        return copy.deepcopy(resource)

class ResourceComparer:
    """资源比较器"""
    
    def __init__(self):
        """初始化比较器"""
        self.ignore_paths = [
            "root['metadata']['creationTimestamp']",
            "root['metadata']['resourceVersion']",
            "root['metadata']['uid']",
            "root['metadata']['generation']",
            "root['status']"
        ]
    
    def compare(
        self,
        resource1: Dict[str, Any],
        resource2: Dict[str, Any],
        ignore_paths: Optional[List[str]] = None
    ) -> Dict[str, Any]:
        """
        比较两个资源
        
        Args:
            resource1: 第一个资源
            resource2: 第二个资源
            ignore_paths: 要忽略的路径列表
            
        Returns:
            差异信息
        """
        # 合并忽略路径
        paths = self.ignore_paths + (ignore_paths or [])
        
        # 计算差异
        diff = deepdiff.DeepDiff(
            resource1,
            resource2,
            ignore_order=True,
            exclude_paths=paths
        )
        
        return {
            "changed": bool(diff),
            "differences": diff,
            "summary": self._summarize_diff(diff)
        }
    
    def _summarize_diff(self, diff: Dict[str, Any]) -> Dict[str, Any]:
        """
        总结差异
        
        Args:
            diff: 差异信息
            
        Returns:
            差异摘要
        """
        summary = {
            "added": len(diff.get("dictionary_item_added", [])),
            "removed": len(diff.get("dictionary_item_removed", [])),
            "modified": len(diff.get("values_changed", [])),
            "type_changes": len(diff.get("type_changes", [])),
            "set_changes": len(diff.get("set_item_added", [])) + len(diff.get("set_item_removed", []))
        }
        
        return summary

class ResourceMerger:
    """资源合并器"""
    
    def __init__(self):
        """初始化合并器"""
        self.strategy = "deep"  # deep, shallow, custom
    
    def merge(
        self,
        resources: List[Dict[str, Any]],
        strategy: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        合并多个资源
        
        Args:
            resources: 资源列表
            strategy: 合并策略
            
        Returns:
            合并后的资源
        """
        if not resources:
            return {}
        
        # 使用指定的策略
        strategy = strategy or self.strategy
        
        if strategy == "deep":
            return self._deep_merge(resources)
        elif strategy == "shallow":
            return self._shallow_merge(resources)
        else:
            raise ValueError(f"不支持的合并策略: {strategy}")
    
    def _deep_merge(self, resources: List[Dict[str, Any]]) -> Dict[str, Any]:
        """深度合并"""
        result = copy.deepcopy(resources[0])
        
        for resource in resources[1:]:
            self._merge_dict(result, resource)
        
        return result
    
    def _shallow_merge(self, resources: List[Dict[str, Any]]) -> Dict[str, Any]:
        """浅层合并"""
        result = {}
        
        for resource in resources:
            result.update(resource)
        
        return result
    
    def _merge_dict(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:
        """
        合并字典
        
        Args:
            target: 目标字典
            source: 源字典
        """
        for key, value in source.items():
            if key in target:
                if isinstance(target[key], dict) and isinstance(value, dict):
                    self._merge_dict(target[key], value)
                elif isinstance(target[key], list) and isinstance(value, list):
                    target[key].extend(value)
                else:
                    target[key] = value
            else:
                target[key] = copy.deepcopy(value)
    
    def merge_with_strategy(
        self,
        resources: List[Dict[str, Any]],
        strategy_config: Dict[str, str]
    ) -> Dict[str, Any]:
        """
        使用自定义策略合并资源
        
        Args:
            resources: 资源列表
            strategy_config: 策略配置
            
        Returns:
            合并后的资源
        """
        result = copy.deepcopy(resources[0])
        
        for resource in resources[1:]:
            for path, strategy in strategy_config.items():
                self._apply_strategy(result, resource, path, strategy)
        
        return result
    
    def _apply_strategy(
        self,
        target: Dict[str, Any],
        source: Dict[str, Any],
        path: str,
        strategy: str
    ) -> None:
        """
        应用合并策略
        
        Args:
            target: 目标资源
            source: 源资源
            path: 路径
            strategy: 策略
        """
        # 解析路径
        parts = path.split(".")
        current_target = target
        current_source = source
        
        # 导航到目标位置
        for part in parts[:-1]:
            if part not in current_target:
                current_target[part] = {}
            if part not in current_source:
                return
            current_target = current_target[part]
            current_source = current_source[part]
        
        # 获取最后一个部分
        last_part = parts[-1]
        
        # 应用策略
        if strategy == "replace":
            if last_part in current_source:
                current_target[last_part] = copy.deepcopy(current_source[last_part])
        elif strategy == "merge":
            if last_part in current_source:
                if isinstance(current_target[last_part], dict):
                    self._merge_dict(current_target[last_part], current_source[last_part])
                elif isinstance(current_target[last_part], list):
                    current_target[last_part].extend(current_source[last_part])
        elif strategy == "append":
            if last_part in current_source:
                if isinstance(current_target[last_part], list):
                    current_target[last_part].extend(current_source[last_part])
        elif strategy == "prepend":
            if last_part in current_source:
                if isinstance(current_target[last_part], list):
                    current_target[last_part] = current_source[last_part] + current_target[last_part]
        else:
            raise ValueError(f"不支持的策略: {strategy}") 